﻿using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using TakePhotoTogether.Controller;
using TakePhotoTogether.Model;
using TakePhotoTogether.Resources;

namespace TakePhotoTogether
{
    public partial class GalleryPage : PhoneApplicationPage
    {
        private readonly string cameraRoll = "C:\\Data\\Users\\Public\\Pictures\\Camera Roll\\";

        private LensViewModel viewModel = new LensViewModel();
        private ApplicationBarMenuItem deleteButton;
        private ApplicationBarMenuItem shareButton;

        private readonly ShareMediaTask _shareMediaTask = new ShareMediaTask();


        public GalleryPage()
        {
            InitializeComponent();

            this.MediaViewer.FooterVisibility = System.Windows.Visibility.Collapsed;

            this.DataContext = this.viewModel;

            UpdateModel();

            PhotoModel.Singleton.PropertyChanged += PhotoModel_PropertyChanged;
        }

        private void FTU_Loaded(object sender, RoutedEventArgs e)
        {
            FTU.Loaded -= FTU_Loaded;
            FTU.SetParent(this);
        }

        private void UpdateModel()
        {
            PlaceHolderManager.DeleteAllMarkedPlaceholders();

            this.viewModel.LoadCameraRoll();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= PhoneApplicationPage_Loaded;
        }

        private void PhotoModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == PhotoModel.LocalPathPropertyName ||
                e.PropertyName == PhotoModel.LibraryPathPropertyName ||
                e.PropertyName == PhotoModel.OriginalPathPropertyName)
            {
                // Source information for photo may have changed, update information panel
                //SetupInformationPanel();
            }
            else if (e.PropertyName == PhotoModel.ImagePropertyName)
            {
                EndSession();

                if (PhotoModel.Singleton.Image != null)
                {
                    BeginSession(PhotoModel.Singleton.Image);
                }
            }

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //EmptyImage.Visibility = Visibility.Visible;
            FTU.UpdateState("Gallery");
            base.OnNavigatedTo(e);

            UpdateModel();

            MainController.Singleton.SetCurrentScreen("GalleryPage", GoMainPage);
        }


        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            Debug.WriteLine("OnNavigatedFrom");
        }

        private void GoMainPage()
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (NavigationService != null)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
                }
            });
        }

        private void BeginSession(Stream image)
        {


        }

        private void EndSession()
        {

        }

        private void CropButton_Click(object sender, EventArgs e)
        {

        }

        #region MediaViewer event handlers

        private void MediaViewer_FooterDisplayed(object sender, EventArgs e)
        {
            //SetAppBarMode(AppBarModeEnum.Viewfinder);
        }

        private void MediaViewer_ItemDisplayed(object sender, ItemDisplayedEventArgs e)
        {
            if (this.MediaViewer.Items != null &&
                this.MediaViewer.Items[(int)e.ItemIndex] is MediaLibraryThumbnailedImage)
            {
                //SetAppBarMode(AppBarModeEnum.MediaLibraryPhoto);
            }
            else if (this.MediaViewer.Items != null &&
                     this.MediaViewer.Items[(int)e.ItemIndex] is LocalFolderThumbnailedImage)
            {
                //SetAppBarMode(AppBarModeEnum.IsolatedStoragePhoto);
            }
            else
            {
                //SetAppBarMode(AppBarModeEnum.Empty);
            }
        }

        private void MediaViewer_ItemUnzoomed(object sender, EventArgs e)
        {
            /*
            if (this.ApplicationBar.IsVisible == false)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    RefreshAppBar();
                });
            }
             * */
        }

        private void MediaViewer_ItemZoomed(object sender, EventArgs e)
        {
            /*
            Dispatcher.BeginInvoke(() =>
            {
                this.ApplicationBar.IsVisible = false;
            });
             * */
        }

        #endregion

        #region User event handlers

        private void OnLeftArrowButtonTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            e.Handled = true;

            if (this.MediaViewer.DragEnabled)
            {
                this.MediaViewer.ScrollLeftOneElement();
            }
        }

        #endregion

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            EmptyImage.Visibility = Visibility.Collapsed;
            this.MediaViewer.FooterVisibility = System.Windows.Visibility.Visible;
            this.DataContext = null;

            EndSession();

            if (viewModel != null)
            {
                viewModel.Dispose();
                viewModel = null;
            }
            if (deleteButton != null)
            {
                GC.SuppressFinalize(deleteButton);
                deleteButton = null;
            }

            if (shareButton != null)
            {
                GC.SuppressFinalize(shareButton);
                shareButton = null;
            }

            if (this.MediaViewer != null)
            {
                this.MediaViewer.Dispose();
                this.MediaViewer = null;
            }

            base.OnBackKeyPress(e);
        }

        void ApplicationBar_StateChanged(object sender, ApplicationBarStateChangedEventArgs e)
        {
            var appBar = sender as ApplicationBar;
            Storyboard storyboard = e.IsMenuVisible ? (Storyboard)Resources["AppBarFadeInStoryboard"] : (Storyboard)Resources["AppBarFadeOutStoryboard"];
            storyboard.Begin();
        }

        void shareButton_Click(object sender, EventArgs e)
        {
            int index = this.MediaViewer.DisplayedItemIndex;

            if (this.MediaViewer.Items[index] is MediaLibraryThumbnailedImage)
            {
                MediaLibraryThumbnailedImage MediaLibraryImage = this.viewModel.PathImageMediaLibrary(index);

                _shareMediaTask.FilePath = cameraRoll + MediaLibraryImage.Picture.Name + ".jpg";
                try
                {
                    _shareMediaTask.Show();
                }
                catch { }
            }
        }
    }
}